<?php
class question extends baseController {    
	public function __construct() {
		parent::__construct ();
	}
    
    public function loadView($temp) {
        if (!isset($temp['data']))
            $temp['data'] = '';
        $this->load->view('index', $temp);
    }
    
    public function index($slug = null) {
        $this->session->set_userdata('selectedcategory', 'mang-xa-hoi');
        if(true) {
            if($slug != null) {
                $questions = $this->questionModel->get_by('slug', $slug);
            }
            if($slug == null || count($questions)==0) {
                $questions = $this->questionModel->get_order_by(null, 'id', 'DESC');
            }
            
            $result = array();
            $accounts = array(0=>'');
            foreach($questions as $k=>$v) {
                $accountid = $v['accountid'];
                $answerid = $v['answerid'];
                if(!isset($accounts[$accountid])) {
                    $acc = $this->accountModel->read($accountid);
                    $accounts[$accountid] = $acc['username'];
                }
                if(!isset($accounts[$answerid])) {
                    $acc = $this->accountModel->read($answerid);
                    $accounts[$answerid] = $acc['username'];
                }
                $v['accountid'] = $accounts[$accountid];
                $v['answerid'] = $accounts[$answerid];
                
                //add comment
                $cms = array();
                $comments = $this->commentModel->get_order_where(null, 'id', 'DESC', array('questionid' => $v['id']));
                foreach($comments as $key=>$value) {
                    $accountid = $value['accountid'];
                    if(!isset($accounts[$accountid])) {
                        $acc = $this->accountModel->read($accountid);
                        $accounts[$accountid] = $acc['username'];
                    }
                    $value['accountid'] = $accounts[$accountid];
                    $cms[] = $value;
                }
                // end add comments
                
                $v['comments'] = $cms;
                
                $result[] = $v;
            }
            
            $this->_data['template'] = 'question';
            $this->_data['questions'] = $result;
            /*
            echo '<pre>';
            print_r($result);
            echo '</pre>';*/
            $this->loadView($this->_data);
        }
    }
}
?>